import json

import taobao_open
from django.db import connection

from app import settings
from app.decorator import app_auth_hook
from app.my_exception import MyException
from app.service import tbk, member
from libs import common
from libs.app_helper import resp_success, resp_error
from libs.db import DB
from libs.form import RawJsonForm

'''
文档：
https://open.taobao.com/doc.htm?docId=118&docType=1
淘宝认证：
https://oauth.taobao.com/authorize?spm=a219a.15212433.0.0.609d669aTdMt6U&response_type=code&client_id=33328606&redirect_uri=http://8.134.70.157:8800/app/tbk_auth_callback&state=15684546419&view=web
接口响应：
{"code": 0, "data": {"token_result": "{"w1_expires_in":86400,"refresh_token_valid_time":1645234237188,"taobao_user_nick":"plftzk","re_expires_in":2592000,"expire_time":1642728637188,"token_type":"Bearer","access_token":"6201604ceb9ceg30ba20a2390b2e63fc9c10c50dd21674330505838","taobao_open_uid":"AAHp2R73ANxGccqB_HlDIje-","w1_valid":1642728637188,"refresh_token":"6201b0418933ZZd46a06164abb2f79ae2ffb9e1850c4eea30505838","w2_expires_in":1800,"w2_valid":1642644037188,"r1_expires_in":86400,"r2_expires_in":86400,"r2_valid":1642728637188,"r1_valid":1642728637188,"taobao_user_id":"30505838","expires_in":86400}", "request_id": "5eokq8vrkxyp"}}
'''


def callback(request):
    GET = request.GET
    code = GET.get('code', '')
    special_id = ''
    if code != '':
        username = GET.get('state', '')
        if username == '':
            return resp_error('用户名称不能为空')
        db_mem = member.get_member_by_username(username, ['id'])
        db_mem_id = db_mem.get('id', 0)
        if db_mem_id == 0:
            return resp_error('用户信息不存在')

        req = taobao_open.api.TopAuthTokenCreateRequest(port=443)
        req.set_app_info(taobao_open.appinfo(settings.TBK_APP_KEY, settings.TBK_APP_SECRET))
        req.code = code
        try:
            with connection.cursor() as cursor:
                dh = DB('cs_tbk_auth', conn=cursor)
                db_tbk_auth = dh.one(['special_id'], {'mem_id': db_mem_id})
                special_id = db_tbk_auth.get('special_id', '')
                if special_id == '':
                    resp = req.getResponse()
                    auth_token_resp = resp.get('top_auth_token_create_response')
                    token_result = auth_token_resp.get('token_result')
                    token_result_jo = json.loads(token_result)
                    session = token_result_jo.get('access_token')
                    result, err = tbk.sc_publisher_info_save(session, 'SJ5FGM')
                    if err is not None:
                        raise MyException(err)
                    special_id = result['data']['special_id']
                    open_id = token_result_jo.get('taobao_open_uid')
                    nickname = token_result_jo.get('taobao_user_nick')
                    now = common.get_ts()
                    data = {
                        'mem_id': db_mem_id,
                        'open_id': open_id,
                        'nickname': nickname,
                        'special_id': special_id,
                        'created': now,
                    }
                    row_id, err = dh.insert(data)
                    if err is not None:
                        if not dh.is_duplicate:
                            raise MyException('淘宝客账号绑定失败')
        except MyException as e:
            return resp_error(str(e))
        except Exception as e:
            err = '淘宝认证异常'
            print(err, e)
            return resp_error(err)
    return resp_success(special_id=special_id)


@app_auth_hook
def bind_member(request, auth):
    form = RawJsonForm(request.body)
    session = form.get('topAccessToken', '')
    if session == '':
        return resp_error('无效的认证信息')
    username = auth.get('member_id')
    try:
        open_id = form.get('openId')
        nickname = form.get('nick')
        db_mem = member.get_member_by_username(username, ['id'])
        db_mem_id = db_mem.get('id', 0)
        if db_mem_id == 0:
            return resp_error('用户信息不存在')
        result, err = tbk.sc_publisher_info_save(session, 'SJ5FGM')
        if err is not None:
            raise MyException(err)
        special_id = result['data']['special_id']
        now = common.get_ts()
        data = {
            'mem_id': db_mem_id,
            'open_id': open_id,
            'nickname': nickname,
            'special_id': special_id,
            'created': now,
        }
        with connection.cursor() as cursor:
            dh = DB('cs_tbk_auth', conn=cursor)
            row_id, err = dh.insert(data)
            if err is not None:
                if not dh.is_duplicate:
                    raise MyException('淘宝客账号绑定失败')
    except Exception as e:
        err = '淘宝认证异常'
        print(err, e)
        return resp_error(err)
    return resp_success({'special_id': special_id})
